<template>
  <div>
    <Upload action="//www.baidu.com" :before-upload="beforeUpload">
      <Button v-if="!result" icon="ios-cloud-upload-outline"
        >Upload files</Button
      >
      <img v-else :src="result" alt="" width="200" />
    </Upload>
    <Modal
      v-model="visible"
      :fullscreen="true"
      title="图片裁剪"
      @on-ok="cropSuccess"
    >
      <vueCropper
        ref="cropper"
        :img="option.img"
        :outputSize="option.size"
        :outputType="option.outputType"
        :info="true"
        :full="option.full"
        :canMove="option.canMove"
        :canMoveBox="option.canMoveBox"
        :original="option.original"
        :autoCrop="option.autoCrop"
        :autoCropWidth="option.autoCropWidth"
        :autoCropHeight="option.autoCropHeight"
        :fixedBox="option.fixedBox"
        :fixed="option.fixed"
        :fixedNumber="option.fixedNumber"
      ></vueCropper>
    </Modal>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { VueCropper } from "vue-cropper";

export default {
  name: "index",
  components: {
    VueCropper
  },
  props: {
    value: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      option: {
        img: null,
        outputSize: 1, //剪切后的图片质量（0.1-1）
        full: false, //输出原图比例截图 props名full
        outputType: "jpg",
        canMove: true,
        original: false,
        canMoveBox: true,
        autoCrop: true,
        autoCropWidth: 450,
        autoCropHeight: 220,
        fixedBox: false,
        fixed: true,
        maxImgSize: 3000, // 图片最大像素
        fixedNumber: [450, 220]
      },
      visible: false,
      result: this.value
    };
  },
  methods: {
    ...mapActions(["upload"]),
    async beforeUpload(img) {
      const read = new FileReader();
      read.onload = e => {
        this.option.img = e.target.result;
        this.visible = true;
      };
      await read.readAsDataURL(img);
      return Promise.reject(false);
    },
    cropSuccess() {
      this.$refs.cropper.getCropBlob(async data => {
        // TODO: 掉上传图片的api
        const formData = new FormData();
        formData.append("img", data, "img.jpg");
        const res = await this.upload(formData);
        if (res.code === 2001) {
          this.$Message.success("上传图片成功");
          this.$refs.cropper.getCropData(data => {
            this.result = data;
          });
          this.$emit("input", res.data.url);
          return;
        }
        this.$Message.error("上传图片失败");
        // this.$emit("input", data);
      });
    }
  }
};
</script>

<style lang="less" scoped></style>
